package com.wsx.ones.language.trans.service.impl;

import com.google.common.base.Strings;
import com.wsx.ones.common.http.HttpClientUtil;
import com.wsx.ones.finalstr.common.BaiduTransUtil;
import com.wsx.ones.finalstr.common.CommonFinalUtil;
import com.wsx.ones.language.common.BaiduConfig;
import com.wsx.ones.language.common.BaiduParamUtil;
import com.wsx.ones.language.trans.bo.TransLangBo;
import com.wsx.ones.language.trans.service.TransLangService;
import com.wsx.ones.language.trans.vo.TransLangVo;
import com.wsx.ones.web.swap.ReturnStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangshuaixin on 17/1/5.
 */
@Service
public class TransLangServiceImpl implements TransLangService {


    public TransLangVo trans(TransLangBo bo) {

        Map<String, String> params = new HashMap<String, String>();
        params.put(BaiduTransUtil.SOURCE_CONTENT, bo.getContent());
        params.put(BaiduTransUtil.FROM_LANGUAGE, bo.getFromLang());
        params.put(BaiduTransUtil.TO_LANGUAGE, bo.getToLang());

        params.put(BaiduTransUtil.TRANS_APPID, BaiduConfig.getAppId());
        params.put(BaiduTransUtil.TRANS_SALT, BaiduConfig.getSalt());

        params.put(BaiduTransUtil.TRANS_SIGN, BaiduParamUtil.getSign(params));

        String result = CommonFinalUtil.STRING_EMPTY;
        try {
            result = HttpClientUtil.doPost(BaiduConfig.getUrl(), params);
        } catch (Exception e) {
            return new TransLangVo(ReturnStatus.ERROR_UNKNOW);
        }

        if (Strings.isNullOrEmpty(result)) {
            return new TransLangVo(ReturnStatus.ERROR_UNKNOW);
        }

        JSONObject jsonObject = new JSONObject(result);

        String transResult = CommonFinalUtil.STRING_EMPTY;
        String error_code = CommonFinalUtil.SUCCESS;
        try {
            if (jsonObject.has(error_code)) {
                error_code = jsonObject.getString("error_code");
            }
            if (!CommonFinalUtil.SUCCESS.equals(error_code)) {
                System.out.println("出错代码:" + error_code);
                System.out.println("出错信息:" + jsonObject.getString("error_msg"));
                return new TransLangVo(ReturnStatus.ERROR_UNKNOW);
            }

            JSONArray jsonArray = (JSONArray) jsonObject.get("trans_result");
            JSONObject dst = (JSONObject) jsonArray.get(0);
            transResult = dst.getString("dst");
            transResult = URLDecoder.decode(transResult, CommonFinalUtil.CHARSET_STR);
        } catch (Exception e) {

        }

        TransLangVo vo = new TransLangVo();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rtncode", error_code);
        map.put("rtn", transResult);
        vo.setResult(map);

        return vo;
    }
}
